package logic

import (
	"afb/models/cache"
	"afb/models/mysql"
	"afb/pkg"
	"afb/zfbrpc/internal/svc"
	"afb/zfbrpc/zfbrpc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *zfbrpc.RegisterRequest) (*zfbrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile)
	if get.Val() != in.CaptChaCode {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}
	cmd := cache.Rdb.Get(l.ctx, "captcha"+in.Username)
	if cmd.Val() != in.CaptChaCode {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}
	var users mysql.Userr
	mysql.DB.Debug().Where("username =?", in.Username).Find(&users)
	if users.ID != 0 {
		return nil, fmt.Errorf("账号已存在,请前去登录")
	}
	user := mysql.Userr{
		Username: in.Username,
		Password: pkg.Md5(in.Password),
	}

	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &zfbrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
